package ldh.im.fxgui.component.cell;

import com.jfoenix.controls.JFXDialog;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.DirectoryChooser;
import ldh.im.fxbase.dao.ImMessageDao;
import ldh.im.fxbase.data.pojo.ImFile;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.data.pojo.ImSession;
import ldh.im.fxbase.data.pojo.ImUser;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.controller.sub.TransferMessageController;
import ldh.im.fxgui.handle.CollectHandler;
import ldh.im.fxgui.util.UiUtil;
import ldh.im.util.ConfigUtil;
import ldh.im.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;


public class FileView extends GridPane {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileView.class);

    private ImFile imFile;
    private Pane popupPane = null;

    public FileView(ImFile imFile) {
        this.imFile = imFile;
        this.getStyleClass().add("file-view");
        initUi();
        bindEvent();
    }

    private void bindEvent() {
        this.addEventFilter(MouseEvent.MOUSE_CLICKED, e->{
            if (e.getButton() == MouseButton.PRIMARY) {
                open(null);
            } else if (e.getButton() == MouseButton.SECONDARY) {
                showPopup(e);
            }
        });
    }

    private void showPopup(MouseEvent e) {
        if (popupPane == null) {
            popupPane = createPopupPane();
        }
        UiUtil.getMainPopup().getContent().setAll(popupPane);
        UiUtil.getMainPopup().show(this.getScene().getWindow(), e.getScreenX(), e.getScreenY());
    }

    private void initUi() {
        // 文件图标
        Label fileIconLabel = new Label();
        fileIconLabel.getStyleClass().add("file-icon");
        fileIconLabel.setGraphic(FileUtil.getFileIcon(imFile.getSuffix()));

        // 文件名称
        Label fileNameLabel = new Label(imFile.getFileName());
        fileNameLabel.getStyleClass().add("file-name");
        // 文件信息：发送者，群名
        TextFlow textFlow = new TextFlow();
        textFlow.getStyleClass().add("file-content");
        ImUser imUser = ImCacheFactory.getInstance().getUser(imFile.getUserId());
        Text sendUserNameText = new Text(imUser.getUserName());

        ImSession session = imFile.getSession();
        String sessionName = session.getName();
        if (session.isP2p()) {
            sessionName = String.format("与%s的聊天", session.getName());
        }

        Text text = new Text(sessionName);
        textFlow.getChildren().addAll(sendUserNameText, new Text(" | "), text);
        VBox vBox = new VBox();
        vBox.getChildren().addAll(fileNameLabel, textFlow);

        Label dateLabel = new Label(DateUtil.format(imFile.getCreateTime(), "yyyy-MM-dd"));
        dateLabel.getStyleClass().add("file-date");
        Label fileSizeLabel = new Label(FileUtil.formatFileSize(imFile.getFileSize()));
        fileSizeLabel.getStyleClass().add("file-size");

        this.getChildren().addAll(fileIconLabel, fileNameLabel, textFlow, dateLabel, fileSizeLabel);

        GridPane.setConstraints(fileIconLabel, 0, 0, 1, 2);

        GridPane.setConstraints(fileNameLabel, 1, 0, 1, 1);
        GridPane.setConstraints(textFlow, 1, 1, 1, 1);

        GridPane.setConstraints(dateLabel, 2, 0, 1, 1);
        GridPane.setConstraints(fileSizeLabel, 2, 1, 1, 1);

        ColumnConstraints c1 = new ColumnConstraints();
        ColumnConstraints c2 = new ColumnConstraints();
        c2.setHgrow(Priority.ALWAYS);
        ColumnConstraints c3 = new ColumnConstraints();

        this.getColumnConstraints().addAll(c1, c2, c3);
    }

    private VBox createPopupPane() {
        VBox vBox = new VBox();
        vBox.getStyleClass().add("file-popup-pane");
        vBox.getChildren().add(RegionUtil.createButton("复制", this::copy));
        vBox.getChildren().add(RegionUtil.createButton("转发", this::transfer));
        vBox.getChildren().add(RegionUtil.createButton("收藏", this::collect));
        vBox.getChildren().add(new Separator());
        vBox.getChildren().add(RegionUtil.createButton("打开", this::open));
        vBox.getChildren().add(RegionUtil.createButton("另存为", this::saveAs));
        vBox.getChildren().add(RegionUtil.createButton("在文件中显示", this::showOnDir));
        vBox.getChildren().add(new Separator());
        vBox.getChildren().add(RegionUtil.createButton("删除", this::delete));
        return vBox;
    }

    private void copy(ActionEvent actionEvent) {

    }

    private void transfer(ActionEvent actionEvent) {
        Task<ImMessage> messageTask = createLoadMessageTask();
        ThreadPoolUtil.submitTask(messageTask);
        messageTask.setOnSucceeded(s->{
            RegionUtil.FxmlBean<Pane, TransferMessageController> fxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/sub/TransferMessagePane.fxml"));
            JFXDialog dialog = DialogUtil.show(fxmlBean.getNode(), false);

            fxmlBean.getController().setDialog(dialog);
            fxmlBean.getController().setTransferImages(Arrays.asList(messageTask.getValue()), true);
            UiUtil.getMainPopup().hide();
        });

    }

    private void collect(ActionEvent actionEvent) {
        Task<ImMessage> messageTask = createLoadMessageTask();
        ThreadPoolUtil.submitTask(messageTask);
        messageTask.setOnSucceeded(s->{
            CollectHandler collectHandler = BeanFactory.getInstance().getBean(CollectHandler.class);
            collectHandler.collectMessage(StageUtil.getRoot(), messageTask.getValue());
            UiUtil.getMainPopup().hide();
        });
    }

    private void open(ActionEvent actionEvent) {
        if (actionEvent != null) {
            UiUtil.getMainPopup().hide();
        }
        String path = ConfigUtil.getRoot() + imFile.getPath();
        if (imFile.getRelativePath() == null || !imFile.getRelativePath()) {
            path = imFile.getPath();
        }
        LOGGER.info("showDocument path: {}", path);
        StageUtil.getHostServices().showDocument(path);
    }

    private void saveAs(ActionEvent actionEvent) {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        File dir = directoryChooser.showDialog(this.getScene().getWindow());
        if (dir == null) return;

        File newFile = new File(dir, imFile.getFileName());
        if (newFile.exists()) {
            DialogUtil.alert("提醒", "文件已存在");
            return;
        }
        ThreadPoolUtil.submit(()->{
            try {
                String fromPath = imFile.getPath();
                if (imFile.getRelativePath() != null && imFile.getRelativePath()) {
                    fromPath = ConfigUtil.getRoot() + imFile.getPath();
                }
                Files.copy(Paths.get(fromPath), newFile.toPath());
            } catch (Exception e) {
                LOGGER.error("复制文件失败", e);
            }
        });
    }

    private void showOnDir(ActionEvent actionEvent) {
        ThreadPoolUtil.submit(()->{
            try {
                String path = ConfigUtil.getRoot() + imFile.getPath();
                if (imFile.getRelativePath() == null || !imFile.getRelativePath()) {
                    path = imFile.getPath();
                }
                File file = new File(path);

                FileUtil.openFileDirCommand(file.getParent());
            } catch (Exception ee) {
                LOGGER.error("打开目录失败", ee);
            }

        });
    }

    private void delete(ActionEvent actionEvent) {

    }

    private Task<ImMessage> createLoadMessageTask() {
        Task<ImMessage> messageTask = new Task() {

            @Override
            protected Object call() throws Exception {
                String userId = UiUtil.getLoginImUser().getUserId();
                ImMessageDao messageDao = BeanFactory.getInstance().getBean(ImMessageDao.class);
                ImMessage imMessage = messageDao.getMessageByServerId(userId, imFile.getMessageId());
                return imMessage;
            }
        };
        return messageTask;
    }

}
